package ac.svn.accesscontrol.ui;

import java.awt.Color;

import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.Highlighter;
import javax.swing.text.JTextComponent;

public class XHighlighter {
    private JTextComponent targetText;
    private XHighLightPainter xHighlightPainter;
    public XHighlighter(JTextComponent textComponent)
    {
	this.targetText = textComponent;
	xHighlightPainter = new XHighLightPainter(new Color(152, 245, 255));
    }

    public void highlight(String pattern)
    {
	removeHighlights();
	// First remove all old highlights     removeHighlights(textComp); 
	try 
	{     
	    Highlighter hilite = targetText.getHighlighter(); 
	    Document doc = targetText.getDocument();   
	    String text = doc.getText(0, doc.getLength());
	    
	    int pos = 0;  
	    // Search for pattern   
	    // see I have updated now its not case sensitive   
	    while ((pos = text.toUpperCase().indexOf(pattern.toUpperCase(), pos)) >= 0) 
	    {       
		// Create highlighter using private painter and apply around pattern   
		hilite.addHighlight(pos, pos+pattern.length(), xHighlightPainter);  
		pos += pattern.length();     
	    } 
	} 
	catch (BadLocationException e) { } 
    }
    
    
    public void removeHighlights()
    {
	Highlighter hilite = targetText.getHighlighter();
	hilite.removeAllHighlights();
	/*	Highlighter.Highlight[] hilites = hilite.getHighlights();

	for (int i=0; i<hilites.length; i++) {
	    if (hilites[i].getPainter() instanceof XHighlighter) {
		hilite.removeHighlight(hilites[i]);
	    }
	}*/
    }

}
